package com.zzmltc.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzmltc.cmn.listener.DictListener;
import com.zzmltc.cmn.mapper.DictMapper;
import com.zzmltc.cmn.service.DictService;
import com.zzmstc.model.cmn.Dict;
import com.zzmstc.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class DictMapperServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //    根据数据id查询子数据列表
    @Override
    @Cacheable(value ="dict",keyGenerator = "keyGenerator")     //这个注解会把返回的数据放到缓存中
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for (Dict dict:dicts){
            Long dictId = dict.getId();
            Boolean children = this.isChildren(dictId);
            dict.setHasChildren(children);
        }
        return dicts;
    }
//    判断id下面是否有子节点
    private Boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
//    导入数据字典
    @CacheEvict(value ="dict",allEntries = true)   //这注解会把dict中的缓存清空
    @Override
    public void importDictData(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class,new DictListener(baseMapper))
                    .sheet("dict")
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//   导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) {

        try {
//            设置下载信息
            response.setContentType("appliction/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
//        这里放置中文乱码，当然和easyexcel没有关系
            String fileName = "dict";
            fileName = URLEncoder.encode("数字字典","UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
//            查询数据库
            List<Dict> dicts = baseMapper.selectList(null);
//            Dict---》DictEeVo
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict:dicts){
                DictEeVo dictEeVo = new DictEeVo();
                dictEeVo.setId(dict.getId());
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
//            调用方法进行写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict").doWrite(dictEeVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
    //    根据dictcode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
//        如果dictCode为空直接根据value查询
        if (StringUtils.isEmpty(dictCode)){
//            根据value查询
            QueryWrapper<Dict> wrapper=new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{// 如果dictCide不为空
 //        如果dictCode不为空直接根据value查询---得到dict的id值
            QueryWrapper<Dict> wrapper=new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);
            Dict codeDict = baseMapper.selectOne(wrapper);
            Long parent_id = codeDict.getId();
//         根据id值进行查询
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("parent_id",parent_id);
            queryWrapper.eq("value",value);
            Dict finalDict = baseMapper.selectOne(queryWrapper);
            return finalDict.getName();
        }

    }

    //    根据dictCode获取下级字节
    @Override
    public List<Dict> findByDictCode(String dictCode) {
//        根据dictCode获取id
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        Long parent_id = codeDict.getId();

//        然后根据id获取节点
        List<Dict> childData = this.findChildData(parent_id);
        return childData;
    }
}
